package com.mobile2you.nci.android;

import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;

import com.mobile2you.nci.android.data.WebServicesRequest;
import com.mobile2you.nci.android.utils.Utils;

public class Main extends Activity {

	private static Activity activity;

	private class LoaderTask extends AsyncTask<String, String, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			WebServicesRequest.checkUpdate(Main.this);
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			Utils.lancerActiviter(Main.this, Home.class);
		}

	}

	public static void finishMain() {
		if (activity != null) {
			activity.finish();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		activity = this;
		setUpLocation();
		new LoaderTask().execute();
	}

	public void setUpLocation() {
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setSpeedRequired(false);

		if (locationManager != null) {

			String best = locationManager.getBestProvider(criteria, false);
			Utils.userLocation = locationManager.getLastKnownLocation(best);
			if (Utils.userLocation == null) {
				Utils.userLocation = locationManager
						.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			}

			if (Utils.userLocation == null) {
				Utils.userLocation = locationManager
						.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			}

			if (Utils.userLocation == null) {
				Utils.userLocation = new Location(LocationManager.GPS_PROVIDER);
				Utils.userLocation.setLatitude(48.734002);
				Utils.userLocation.setLongitude(2.270368);
			}

			LocationListener listener = new LocationListener() {
				@Override
				public void onLocationChanged(Location location) {
					Utils.userLocation = location;
				}

				@Override
				public void onProviderDisabled(String provider) {
				}

				@Override
				public void onProviderEnabled(String provider) {
				}

				@Override
				public void onStatusChanged(String provider, int status,
						Bundle extras) {
				}
			};

			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 100, 0, listener);

		}

	}
}